package com.xc.content.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xc.content.mapper.CourseCategoryMapper;
import com.xc.content.model.dto.CourseCategoryDto;
import com.xc.content.model.po.CourseCategory;
import com.xc.content.service.CourseCategoryService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class CourseCategoryServiceImpl extends ServiceImpl<CourseCategoryMapper, CourseCategory> implements CourseCategoryService {
    @Autowired
    private CourseCategoryMapper courseCategoryMapper;

    @Override
    public List<CourseCategoryDto> queryTreeNodes(String id) {
        List<CourseCategoryDto> list = courseCategoryMapper.queryTreeNodes(id).stream().filter(c -> !c.getId().equals(id)).collect(Collectors.toList());

        //list 转换成map
        Map<String, CourseCategoryDto> courseCategoryMap = list.stream().collect(Collectors.toMap(CourseCategoryDto::getId, Function.identity()));
        List<CourseCategoryDto> categoryDtos = new ArrayList<>();
        list.stream().forEach(item -> {
            //父节点是传过来的查询参数，作为一级节点
            if (item.getParentid().equals(id)) {
                categoryDtos.add(item);
            } else {
                //其他属于子节点，自己自己的父亲节点
                CourseCategoryDto parent = courseCategoryMap.get(item.getParentid());
                if (parent.getChildrenTreeNodes() == null) {
                    List<CourseCategoryDto> tempList = new ArrayList<>();
                    tempList.add(item);
                    parent.setChildrenTreeNodes(tempList);
                } else {
                    parent.getChildrenTreeNodes().add(item);
                }
            }

        });

        return categoryDtos;
    }
}
